package m4_rowting;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {

        ConnectionFactory f=new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c=f.newConnection().createChannel();

        c.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);
        String queue=c.queueDeclare().getQueue();
        System.out.println("输入绑定建,用空格隔开:");
        String s=new Scanner(System.in).nextLine();
        String[] a=s.split("\\s+");
        for (String key:a){
            c.queueBind(queue,"direct_logs","");
        }

        DeliverCallback deliverCallback=new DeliverCallback(){
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                String msg=new String(delivery.getBody(),"UTF-8");
                String key=delivery.getEnvelope().getRoutingKey();
                //System.out.println("收到:"+msg);
                for (int i = 0; i < msg.length(); i++) {
                    if (msg.charAt(i)=='.') {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
                c.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
                System.out.println("处理结束--------------");
            }
        };
        CancelCallback cancelCallback=new CancelCallback(){
            @Override
            public void handle(String s) throws IOException {
            }
        };
        //服务器自动命名
        //String queue=c.queueDeclare().getQueue();

        c.queueBind(queue,"direct_logs","");
        c.basicConsume("direct_logs",true,deliverCallback,cancelCallback);
    }
}
